<?php

class AuthController extends Zend_Controller_Action
{
    public function init()
    {
        $this->db   = Zend_Registry::get('db');
    }

    public function indexAction()
    {

        $cfg = new Zend_Config_Ini(  APPLICATION_PATH . '/configs/application.ini', 'production' );

        require 'facebook.php';

        $fb = new Facebook(array(
          'appId'  => $cfg->facebook->appId,
          'secret' => $cfg->facebook->secret,
          'cookie' => true
        ));

        $session = $fb->getSession();

        if ( $session ) {
        	try {
        		$uid = $fb->getUser();
        	} catch ( FacebookApiException $e ) {
        		$this->_redirect('/auth');
        	}

        	$auth 	= Zend_Auth::getInstance();

        	$this->db->setFetchMode(Zend_Db::FETCH_OBJ);
        	$usrObj = $this->db->fetchRow( 'SELECT Id FROM Usrs WHERE Id = ?', $uid );

        	if ( !$usrObj ){					// If new user
        		$usr = $fb->api('/me');

        		if ( $usr['birthday'] ){
        			list( $m, $d, $y) = explode( '/', $usr['birthday'] );
        			$bd = $y.'-'.$m.'-'.$d;
        		}

        		$data = array(
        						'Id' 			=> $usr['id'],
        						'Link' 			=> $usr['link'],
        						'First_name' 	=> $usr['first_name'],
        						'Last_name' 	=> $usr['last_name'],
        						'Locale' 		=> $usr['locale'],
        						'Gender' 		=> $usr['gender'] ? $usr['gender'] : 'male',
        						'BD_Dt' 		=> $bd,
        						'Signup_Dt' 	=> new Zend_Db_Expr('NOW()')
        		);

        		$this->db->insert( 'Usrs', $data );

        		$usrObj 	= new StdClass;
        		$usrObj->Id = (int)$usr['id'];

	        	$auth->getStorage()->write( $usrObj );
	        	$this->_redirect('/profile');
        	}

        	$auth->getStorage()->write( $usrObj );
        	$this->_redirect('/');
        }{
        	$this->view->LoginURL 	= $fb->getLoginUrl(array('req_perms' => 'user_birthday,user_location,publish_stream'));
        	$this->view->appId 		= $cfg->facebook->appId;
        }
    }
}
